package com.ruoyi.tt.service.impl;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.tt.domain.TtHistory;
import com.ruoyi.tt.domain.vo.ArticleVO;
import com.ruoyi.tt.mapper.TtArticleCommentMapper;
import com.ruoyi.tt.mapper.TtArticleMapper;
import com.ruoyi.tt.mapper.TtHistoryMapper;
import com.ruoyi.tt.service.TtHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * @date 2022/10/22 1:05
 **/
@Service
public class TtHistoryServiceImpl implements TtHistoryService {

    @Autowired
    private TtHistoryMapper historyMapper;

    @Autowired
    private TtArticleMapper articleMapper;

    @Autowired
    private TtArticleCommentMapper articleCommentMapper;

    @Override
    public List<ArticleVO> list() {
        Long userId = SecurityUtils.getUserId();// 获取当期那登录的用户id
        // 根据当前用户查询文章id集合
        List<Integer> listIds = historyMapper.getCurrentUserHistory(userId);
        List<ArticleVO> articleVOList = articleMapper.getArticleByArticleIds(listIds);
        articleVOList = articleVOList.stream().map(articleVO -> {
            Integer id = articleVO.getId();
            Integer count = articleCommentMapper.getArticleCommentCountByArticleId(id);
            articleVO.setCount(count == null ? 0 : count);
            return articleVO;
        }).collect(Collectors.toList());
        return articleVOList;
    }

    @Override
    public int save(Integer articleId) {
        Long userId = SecurityUtils.getUserId();
        int count = historyMapper.getHistoryByUserIdWithArticleId(articleId, userId);
        int i = 0;
        if (count > 0) { //  如果可以根据用户文章id查找到记录，就将其创建时间 create_time 进行修改
            TtHistory history = new TtHistory();
            history.setUserId(Math.toIntExact(userId));
            history.setArticleId(articleId);
            i = historyMapper.update(history);
        } else { // 查不到就新增
            TtHistory history = new TtHistory();
            history.setUserId(Math.toIntExact(userId));
            history.setArticleId(articleId);
            Date date = new Date();
            history.setCreateTime(date);
            i = historyMapper.save(history);
        }
        return i;
    }
}
